//
//  BRSupportView.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/10/14.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRSupportView.h"

@interface BRSupportView ()
{
    UIView *_contentView;
    CGFloat _content_h;
    UIButton *_backBtn;
}

@property (nonatomic,strong) BRQRContactView *qrView;

@end

@implementation BRSupportView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUI];
    }
    return self;
}

#pragma mark - Action --
//- (void)btnAction:(UITapGestureRecognizer *)btn {
//    NSInteger index = btn.view.tag;
//    if (index == 200) {
//        [BROpenURL callPhone];
//    }else {
//        [BROpenURL callEMail];
//    }
//}

- (void)hiddQrCode {
    _backBtn.hidden = YES;
    self.qrView.hidden = YES;
}
- (void)showQrCode:(NSInteger)type {
    
    NSString *url = type == 2 ? USERManager.qrCodeWX : USERManager.qrCodeZalo;
    url = [NSString stringWithFormat:@"%@/%@",USERManager.filesSever,url];
    [self.qrView.qrImgView sd_setImageWithURL:[NSURL URLWithString:url]];
    
    _backBtn.hidden = NO;
    self.qrView.hidden = NO;
}

- (void)hidd  {
    
    [UIView animateWithDuration:0.25 animations:^{
        self->_contentView.transform = CGAffineTransformMakeRotation(0);
    } completion:^(BOOL finished) {
        self.hidden =  YES;
        self.qrView.hidden = YES;
    }];
}

- (void)show {
    self.hidden = NO;
    [UIView animateWithDuration:0.25 animations:^{
        self->_contentView.transform = CGAffineTransformMakeTranslation(0, -(self->_content_h));
    }];
}

#pragma mark - set ui --
- (void)setUI {
    _content_h = 334 + kSafeAreaBottomHeight;
    self.backgroundColor = UIColorShadow;
    self.hidden = YES;
    
    UIView *contView  = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, _content_h)];
    contView.backgroundColor = UIColor.whiteColor;
    [self addSubview:contView];
    // 设置顶部圆角
    // 绘制圆角 需设置的圆角 使用"|"来组合
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:contView.bounds byRoundingCorners:UIRectCornerTopLeft |
    UIRectCornerTopRight cornerRadii:CGSizeMake(30, 30)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];

    // 设置大小
    maskLayer.frame = contView.bounds;

    // 设置图形样子
    maskLayer.path = maskPath.CGPath;
    contView.layer.mask = maskLayer;
    _contentView = contView;
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setBackgroundImage:UIImageMake(@"arrow_left_gary44") forState:UIControlStateNormal];
    backBtn.frame = CGRectMake(14, 0, 44, 44);
    backBtn.hidden = YES;
    [_contentView addSubview:backBtn];
    [backBtn addTarget:self action:@selector(hiddQrCode) forControlEvents:UIControlEventTouchUpInside];
    _backBtn = backBtn;
    
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [closeBtn setBackgroundImage:UIImageMake(@"arrow_close_gray44") forState:UIControlStateNormal];
    closeBtn.frame = CGRectMake(kScreenWidth - 60, 0, 44, 44);
    [_contentView addSubview:closeBtn];
    [closeBtn addTarget:self action:@selector(hidd) forControlEvents:UIControlEventTouchUpInside];
   

    BRContactView *contactView = [[BRContactView alloc] init];
    [contView addSubview:contactView];
    [contactView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(32);
        make.right.offset(-32);
        make.top.offset(72);
    }];
    
    self.qrView.hidden = YES;
    [contView addSubview:self.qrView];
    [self.qrView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.offset(0);
        make.top.offset(44);
    }];
    
    WS(weakSelf);
    contactView.br_contactClickBlock = ^(NSInteger index) {
        
        switch (index) {
            case 0:
                // 点击客服电话，跳转到系统拨号页面
                {
                    NSString *phone = USERManager.whatsapp;
                    if (phone.length == 0) {
                        phone = @"0835001799";  // 默认手机号
                    }
                    // 如果电话号码以0开头且没有国家代码，可能需要添加越南国家代码+84
                    // 但先尝试直接拨打，如果失败再考虑添加国家代码
                    [BROpenURL callPhone:phone];
                }
                break;
            case 1:
                
                [BROpenURL callEMail];
                break;
            case 2:
                [weakSelf showQrCode:index];
                break;
            case 3:
                [weakSelf showQrCode:index];
                break;
            default:
                break;
        }
       
    };
    
    return;
    
}

- (BRQRContactView *)qrView {
    
    if (_qrView == nil) {
        _qrView = [[BRQRContactView alloc] init];
    }
    return _qrView;
}

@end

@implementation BRContactView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setUI];
    }
    return self;
}

- (void)btnAction:(UITapGestureRecognizer *)btn {
    NSInteger index = btn.view.tag - 200;
    
    if (index == 1) {
        // copy email 复制邮箱 - 硬编码为 youdianstar@gmail.com
        NSString *eamil = @"youdianstar@gmail.com";
        // 将文本复制到粘贴板
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        [pasteboard setString:eamil];
        // 检查复制是否成功
        if ([pasteboard string] != nil) {
            NSLog(@"文本已成功复制到粘贴板");
            [BRHud showAuto:Localized(@"invite_copied")];
        } else {
            NSLog(@"无法复制文本到粘贴板");
            [BRHud showAuto:Localized(@"public_failed")];
        }
        return;
    }
    
    if (self.br_contactClickBlock) {
        self.br_contactClickBlock(index);
    }
}

- (void)setContactEmail:(NSString *)contactEmail {
    _contactEmail = contactEmail;
    QMUILabel *label = (QMUILabel *)[self viewWithTag:501];
    label.text = contactEmail;
    label.attributedText = [BRTools br_addAttBottomLine:contactEmail];
}

- (void)setContactPhone:(NSString *)contactPhone {
    _contactPhone = contactPhone;
    QMUILabel *label = (QMUILabel *)[self viewWithTag:500];
    label.text = contactPhone;
    label.attributedText = [BRTools br_addAttBottomLine:contactPhone];
}

- (void)br_hidden:(BOOL)hidden by:(NSInteger)index {
    UIView *btn = [self viewWithTag:200 + index];
    btn.hidden = hidden;
}


- (void)setUI {
    
    UIStackView *stackView = [[UIStackView alloc] init];
    stackView.axis = UILayoutConstraintAxisVertical;
//    stackView.alignment = UIStackViewAlignmentFill;
//    stackView.distribution = UIStackViewDistributionFillEqually;
    stackView.spacing = 28;
    [self addSubview:stackView];
    [stackView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.left.top.right.offset(0);
        make.bottom.offset(0);
    }];
    _stackView = stackView;
    
    // 处理可能为 nil 的值，避免数组初始化崩溃
    // 联系客服弹窗的手机号使用写死的值 0835001799
    NSString *whatsapp = USERManager.whatsapp;
    if (whatsapp.length == 0) {
        whatsapp = @"0835001799";  // 默认手机号
    }
    // 联系客服弹窗的email硬编码为 youdianstar@gmail.com
    NSString *contactEmail = @"youdianstar@gmail.com";
    NSArray *titles = @[whatsapp, contactEmail/*,Localized(@"help_qrCode")*/];
    NSArray *imgs = @[@"faq_whatsapp" , @"faq_email"/*,@"faq_wechat"*/];
    for (int i = 0; i < imgs.count; i++) {
        
        UIView *btn = [[UIView  alloc] init];
        btn.userInteractionEnabled = YES;
        [stackView addArrangedSubview:btn];
        btn.tag = 200 + i;
        
        UIImageView *img  = [[UIImageView alloc] initWithImage:UIImageMake(imgs[i])];
        img.frame = CGRectMake(0, 0, 28, 28);
        img.userInteractionEnabled = YES;
        [btn addSubview:img];
        [img mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.width.mas_equalTo(28);
            make.top.offset(0);
            make.bottom.offset(0);
            make.left.offset(0);
        }];
        
        QMUILabel *label = [[QMUILabel alloc] init];
        NSString *contactStr = titles[i];
        if (contactStr.length == 0) contactStr = @"--";
        label.tag = 500 + i;
        label.text  = contactStr;
        if (i != 1)  {
            if (![contactStr isEqualToString:@"--"]) {
                label.attributedText = [BRTools br_addAttBottomLine:contactStr];
            }
        }
        label.textColor = kColorMain;
        label.font = [UIFont fontM:17];
        [btn addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(img.mas_centerY).offset(0);
            make.left.equalTo(img.mas_right).offset(8);
        }];
        
        if (i == 1) {
            UIImageView *cpBtn = [[UIImageView alloc] initWithImage:UIImageMake(@"faq_copy")];
            [btn addSubview:cpBtn];
            [cpBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(label.mas_right).offset(4);
                make.centerY.equalTo(img.mas_centerY).offset(0);
                make.height.width.mas_equalTo(20);
            }];
        }
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(btnAction:)];
        [btn addGestureRecognizer:tap];
    }
}



@end


@implementation BRQRContactView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setUI];
    }
    return self;
}

- (void)saveClick {
    
    UIImage *img = self.qrImgView.image;
    
    if (!img) {
        
        NSLog(@"图片不存在");
    }
  
    [self saveClickNext];
}

- (void)saveClickNext {
    UIImage *img = self.qrImgView.image;
    // 将图片保存到相册
    UIImageWriteToSavedPhotosAlbum(img, self , @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
    if (self.saveBlock) self.saveBlock();
}

- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo{

    

    if(!error) {
        
        NSLog(@"保存成功");
        [BRHud showAuto:Localized(@"public_success")];
        
    }else{
        NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
        NSLog(@"保存失败");
//        [BRHud showAuto:@"Save error"];
        [GGPermissionsManage checkPhotosNotDeterminedr:^{
            
        } faile:^{
            
        }];
    }

}


#pragma mark - UI --
- (void)setUI {
    
    self.backgroundColor = UIColor.whiteColor;
    
    NSString *title = self.type == 0 ? Localized(@"help_addWhitWX") : Localized(@"help_addWhitWX");
    QMUILabel *titleL = [BRToolsView br_label:title textColor:kColorTitle font:[UIFont fontS:17]];
    titleL.textAlignment = NSTextAlignmentCenter;
    titleL.numberOfLines = 0;
    [self addSubview:titleL];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(28);
        make.right.offset(-28);
        make.top.offset(20);
    }];
    
    
    self.qrImgView = [[UIImageView alloc] init];
    [self addSubview:self.qrImgView];
    [self.qrImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleL.mas_bottom).offset(24);
        make.centerX.offset(0);
        make.height.width.mas_equalTo(140);
    }];
    
    
    QMUILabel *saveL = [BRToolsView br_label:Localized(@"help_saveQR") textColor:kColorMain font:[UIFont fontS:17]];
    saveL.textAlignment = NSTextAlignmentCenter;
    saveL.numberOfLines = 0;
    saveL.attributedText = [BRTools br_addAttBottomLine:saveL.text];
    [self addSubview:saveL];
    [saveL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(28);
        make.right.offset(-28);
        make.top.equalTo(self.qrImgView.mas_bottom).offset(24);
        make.bottom.offset(-24);
    }];
    
    UIControl *btn = [[UIControl alloc] init];
    [self addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(saveL).offset(0);
        make.right.equalTo(saveL).offset(0);
        make.top.equalTo(saveL.mas_top).offset(-20);
        make.bottom.equalTo(saveL.mas_bottom).offset(20);
    }];
    [btn addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
    
//    self.qrImgView.image = [BRImgTools br_qrLink:@"www.baidu.com"];
    
    
}

@end
